package com.chixing.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfiguration {
    //队列名称
    public final static String couponQueue = "coupon_queue";

    //交换机名称
    public final static String couponExchange = "coupon_exchange";

    // routingKey
    public final static String routingKeycoupon = "routing_key_coupon";

    //死信消息队列名称
    public final static String deadQueuecoupon = "dead_queue_coupon";

    //死信交换机名称
    public final static String deadExchangecoupon = "dead_exchange_coupon";

    //死信 routingKey
    public final static String deadRoutingKeycoupon = "dead_routing_key_coupon";

    //死信队列 交换机标识符
    public static final String DEAD_LETTER_QUEUE_KEY = "x-dead-letter-exchange";

    //死信队列交换机绑定键标识符
    public static final String DEAD_LETTER_ROUTING_KEY = "x-dead-letter-routing-key";

    @Autowired
    private CachingConnectionFactory connectionFactory;

    @Bean
    public Queue couponQueue() {
        // 将普通队列绑定到死信队列交换机上

        Map<String, Object> args = new HashMap<>(2);
        //args.put("x-message-ttl", 5 * 1000);//直接设置 Queue 延迟时间 但如果直接给队列设置过期时间,这种做法不是很灵活

//这里采用发送消息动态设置延迟时间,这样我们可以灵活控制

        args.put(DEAD_LETTER_QUEUE_KEY, deadExchangecoupon);
        args.put(DEAD_LETTER_ROUTING_KEY, deadRoutingKeycoupon);
        return new Queue(RabbitMQConfiguration.couponQueue, true, false, false, args);
    }


    //声明一个direct类型的交换机
    @Bean
    public DirectExchange couponExchange() {
        return new DirectExchange(RabbitMQConfiguration.couponExchange);
    }


    //绑定Queue队列到交换机,并且指定routingKey
    @Bean
    public Binding bindingDirectExchange() {
        return BindingBuilder.bind(couponQueue()).to(couponExchange()).with(routingKeycoupon);
    }


    //创建配置死信队列
    @Bean
    public Queue deadQueuecoupon() {
        Queue queue = new Queue(deadQueuecoupon, true);
        return queue;
    }


    //创建死信交换机
    @Bean
    public DirectExchange deadExchangecoupon() {
        return new DirectExchange(deadExchangecoupon);
    }
    //死信队列与死信交换机绑定
    @Bean
    public Binding bindingDeadExchange() {
        return BindingBuilder.bind(deadQueuecoupon()).to(deadExchangecoupon()).with(deadRoutingKeycoupon);
    }


}
